<template>
  <div class="case-list-container">
    <!-- Filter Card -->
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="filter" class="filter-form">
        <el-form-item label="案件编号">
          <el-input v-model="filter.caseNumber" placeholder="请输入案件编号" clearable />
        </el-form-item>
        <el-form-item label="案件名称">
          <el-input v-model="filter.caseName" placeholder="请输入案件名称" clearable />
        </el-form-item>
        <el-form-item label="立案时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button @click="reset">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- Action Bar -->
    <div class="action-bar">
      <el-button type="primary" @click="openNewCaseModal">
        <el-icon><Plus /></el-icon> 新增案件
      </el-button>
      <el-button type="primary" plain @click="openImportCaseModal">
        <el-icon><Upload /></el-icon> 导入案件
      </el-button>
    </div>

    <!-- Cases Grid -->
    <div class="cases-grid" v-loading="loading">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="c in cases" :key="c.id">
          <el-card class="case-card" shadow="hover" :body-style="{ padding: '0px' }">
            <div class="card-header">
              <div class="header-main">
                <span class="case-name" :title="c.case_name">{{ c.case_name }}</span>
                <el-icon v-if="c.password" class="lock-icon"><Lock /></el-icon>
              </div>
              <div class="header-actions">
                <el-tag v-if="c.case_status" :class="['status-tag', getStatusClass(c.case_status)]" size="small" style="margin-right: 5px">{{ c.case_status }}</el-tag>
                <el-tag v-if="c.closed_status === 1" type="info" size="small" effect="dark">结案</el-tag>
              </div>
            </div>

            <div class="card-body" @click="handleAnalyze(c)">
              <div class="info-item">
                <span class="label">案件编号：</span>
                <span class="value">{{ c.case_number }}</span>
              </div>
              <div class="info-item">
                <span class="label">立案时间：</span>
                <span class="value">{{ formatDate(c.case_start_time) }}</span>
              </div>
              <div class="case-desc" :title="c.description">
                <span class="label">案件简介：</span>
                {{ c.description || '暂无简介' }}
              </div>
            </div>

            <div class="card-footer">
              <div class="footer-actions">
                <div class="action-item" @click="handleImport(c)">
                  <el-icon><Upload /></el-icon>
                  <span>导入</span>
                </div>
                <div class="action-item" @click="handleAnalyze(c)">
                  <el-icon><DataAnalysis /></el-icon>
                  <span>分析</span>
                </div>
                <div class="action-item" @click="handleEdit(c)">
                  <el-icon><Edit /></el-icon>
                  <span>编辑</span>
                </div>
                <div class="action-item delete" @click="handleDelete(c.id)">
                  <el-icon><Delete /></el-icon>
                  <span>删除</span>
                </div>
                <div class="action-item more-action">
                  <el-dropdown trigger="click" @command="(cmd) => handleCommand(cmd, c)" placement="top">
                    <div class="el-dropdown-link">
                      <el-icon><More /></el-icon>
                      <span>更多</span>
                    </div>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item v-if="!c.password" command="encrypt">🔒 设置加密</el-dropdown-item>
                        <el-dropdown-item v-if="c.password" command="updatePass">🔑 修改密码</el-dropdown-item>
                        <el-dropdown-item v-if="c.password" command="removePass">🔓 清除密码</el-dropdown-item>
                        <el-dropdown-item command="export" divided>📤 导出案件</el-dropdown-item>
                        <el-dropdown-item v-if="c.closed_status !== 1" command="close">🚫 结案</el-dropdown-item>
                        <el-dropdown-item v-if="c.closed_status === 1" command="unclose">✅ 取消结案</el-dropdown-item>
                        <el-dropdown-item command="report">📊 分析报告</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-empty v-if="cases.length === 0 && !loading" description="暂无案件数据" />
    </div>

    <!-- Modals -->
    <NewCaseModal v-if="showNewCase" v-model:show="showNewCase" @created="refresh" />
    <EditCaseModal v-if="showEditCase" v-model:show="showEditCase" :case-data="currentCase" @updated="refresh" />
    <ImportCaseModal v-if="showImportCase" v-model:show="showImportCase" @imported="refresh" />
    <ExportCaseModal v-if="showExportCase" v-model:show="showExportCase" :case-id="currentCase?.id" />
    <PasswordModal v-if="showPasswordModal" v-model:show="showPasswordModal" :mode="passwordModalMode" :case-id="currentCase?.id" @success="handlePasswordSuccess" />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useCaseStore } from '../stores/case'
import { ElMessageBox, ElMessage } from 'element-plus'
import NewCaseModal from '../components/NewCaseModal.vue'
import EditCaseModal from '../components/EditCaseModal.vue'
import ImportCaseModal from '../components/ImportCaseModal.vue'
import ExportCaseModal from '../components/ExportCaseModal.vue'
import PasswordModal from '../components/PasswordModal.vue'

const router = useRouter()
const caseStore = useCaseStore()

const filter = ref({
  caseNumber: '',
  caseName: '',
  startDate: '',
  endDate: ''
})
const dateRange = ref([])

const showNewCase = ref(false)
const showEditCase = ref(false)
const showImportCase = ref(false)
const showExportCase = ref(false)
const showPasswordModal = ref(false)
const passwordModalMode = ref('set')
const currentCase = ref(null)

const cases = computed(() => caseStore.cases)
const loading = computed(() => caseStore.loading)

onMounted(() => {
  caseStore.fetchCases()
})

const handleDateChange = (val) => {
  if (val) {
    filter.value.startDate = val[0]
    filter.value.endDate = val[1]
  } else {
    filter.value.startDate = ''
    filter.value.endDate = ''
  }
}

const search = () => {
  caseStore.fetchCases(filter.value)
}

const reset = () => {
  filter.value = {
    caseNumber: '',
    caseName: '',
    startDate: '',
    endDate: ''
  }
  dateRange.value = []
  caseStore.fetchCases()
}

const openNewCaseModal = () => {
  showNewCase.value = true
}

const openImportCaseModal = () => {
  showImportCase.value = true
}

const handleEdit = (c) => {
  currentCase.value = c
  showEditCase.value = true
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该案件吗？此操作不可恢复。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await caseStore.deleteCase(id)
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const refresh = () => {
  caseStore.fetchCases(filter.value)
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleDateString()
}

const getStatusClass = (status) => {
    if (status === '留置') return 'status-detention'
    if (status === '初核') return 'status-preliminary'
    return 'status-normal'
}

const handleImport = (c) => {
  if (c.closed_status === 1) {
    ElMessage.warning('案件已结案，无法导入')
    return
  }
  router.push({ path: '/workbench', query: { caseId: c.id, tab: 'import' } })
}

const handleAnalyze = (c) => {
  router.push({ path: '/workbench', query: { caseId: c.id, tab: 'analysis' } })
}

const handleMore = (c) => {
  // Placeholder for "More" button if needed, currently handled by dropdown
}

const handleCommand = (cmd, c) => {
  currentCase.value = c
  switch (cmd) {
    case 'encrypt':
      passwordModalMode.value = 'set'
      showPasswordModal.value = true
      break
    case 'updatePass':
      passwordModalMode.value = 'update'
      showPasswordModal.value = true
      break
    case 'removePass':
      passwordModalMode.value = 'remove'
      showPasswordModal.value = true
      break
    case 'export':
      showExportCase.value = true
      break
    case 'close':
      handleCloseCase(c)
      break
    case 'unclose':
      handleUncloseCase(c)
      break
    case 'report':
      ElMessage.info('功能开发中...')
      break
  }
}

const handleCloseCase = (c) => {
  ElMessageBox.confirm('确定要结案吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    if (window.electronAPI) {
      await window.electronAPI.case.update({ id: c.id, closed_status: 1 })
      refresh()
      ElMessage.success('已结案')
    }
  }).catch(() => {})
}

const handleUncloseCase = async (c) => {
  if (window.electronAPI) {
    await window.electronAPI.case.update({ id: c.id, closed_status: 0 })
    refresh()
    ElMessage.success('已取消结案')
  }
}

const handlePasswordSuccess = () => {
  refresh()
  ElMessage.success('密码设置成功')
}
</script>

<style scoped>
.case-list-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
  background-color: #f5f7fa;
}

.filter-card {
  border-radius: 4px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.filter-form .el-form-item {
  margin-bottom: 0;
  margin-right: 20px;
}

.action-bar {
  display: flex;
  gap: 10px;
}

.cases-grid {
  flex: 1;
  overflow-y: auto;
}

.case-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;
  border: none;
}

.case-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
}

.card-header {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f2f5;
}

.header-main {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  overflow: hidden;
}

.case-name {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.lock-icon {
  color: #e6a23c;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.more-btn {
  cursor: pointer;
  color: #909399;
  transform: rotate(90deg);
  display: flex;
  align-items: center;
}

.more-btn:hover {
  color: #409eff;
}

.card-body {
  padding: 15px;
  cursor: pointer;
}

.info-item {
  display: flex;
  font-size: 13px;
  color: #606266;
  margin-bottom: 8px;
}

.info-item .label {
  color: #909399;
  width: 70px;
  flex-shrink: 0;
}

.case-desc {
  font-size: 13px;
  color: #606266;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 40px;
  line-height: 1.5;
}

.case-desc .label {
  color: #909399;
}

.card-footer {
  border-top: 1px solid #f0f2f5;
  padding: 10px 0;
}

.footer-actions {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  color: #606266;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s;
}

.action-item:hover {
  color: #409eff;
  background-color: #f5f7fa;
}

.action-item.delete:hover {
  color: #f56c6c;
}

.action-item .el-icon {
  font-size: 16px;
}

/* Fix for dropdown trigger to match other action items */
.more-action {
  padding: 0 !important;
}

.more-action .el-dropdown {
  width: 100%;
  height: 100%;
  display: block;
}

.el-dropdown-link {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  width: 100%;
  height: 100%;
  padding: 4px 8px;
  color: inherit;
  outline: none;
  box-sizing: border-box;
}

.action-item:hover .el-dropdown-link {
  color: #409eff;
}

/* Responsive adjustments */
@media screen and (max-width: 768px) {
  .filter-form .el-form-item {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

.status-tag {
    color: #000000 !important;
    border: none !important;
    font-weight: 600;
}

.status-detention {
    background-color: #ffb6b6 !important; /* Pastel Red */
}

.status-preliminary {
    background-color: #ffe58f !important; /* Pastel Yellow/Orange */
}

.status-normal {
    background-color: #bae7ff !important; /* Pastel Blue */
}
</style>
